package com.zlll.winner.service.bbs.async;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlll.winner.business.model.bbs.BbsPost;
import com.zlll.winner.enums.bbs.ActionLogEnum;
import com.zlll.winner.mapper.bbs.BbsPostMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 帖子异步服务实现类
 * </p>
 *
 * @author Walert
 * @since 2019-09-12
 */
@Service
@Async
@Slf4j
public class BbsPostAsyncService {

    @Resource
    private BbsPostMapper postMapper;

    private int count(long postId,Integer actionType){
        BbsPost bbsPost = postMapper.selectById(postId);
        BbsPost updateObj = new BbsPost();
        updateObj.setUpdateTime(System.currentTimeMillis());
        if(actionType == ActionLogEnum.ActionTypeEnum.LIKE.val()){
            updateObj.setLikeNum(bbsPost.getLikeNum()+1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.RELAY.val()){
            updateObj.setRelayNum(bbsPost.getRelayNum()+1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.COMMENT.val()){
            updateObj.setCommentNum(bbsPost.getCommentNum()+1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.REMOVE_COMMENT.val()){
            updateObj.setCommentNum(bbsPost.getCommentNum()-1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.UNLIKE.val()){
            updateObj.setLikeNum(bbsPost.getLikeNum()-1);
        }
        int update = postMapper.update(updateObj,
                Wrappers.<BbsPost>lambdaQuery()
                        .eq(BbsPost::getId, postId)
                        .eq(BbsPost::getUpdateTime, bbsPost.getUpdateTime()));
        return update;
    }


    @Async
    public void changeNumber(Long postId,Integer actionType) throws InterruptedException {
        int res = 0;
        int sum = 10;
        while(res == 0 && sum > 0){
            res = count(postId,actionType);
            if(res == 0 ) Thread.sleep(500L);
            sum --;
        }
        log.error("统计帖子数量完毕。");
    }
}
